package cn.edu.xmut.chen.zhlg.zhlg.message.config;


import cn.edu.xmut.chen.zhlg.zhlg.message.service.WebSocketSessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

@Slf4j
@Component
public class WebSocketEventListener {
    private final WebSocketSessionService sessionService;

    public WebSocketEventListener(WebSocketSessionService sessionService) {
        this.sessionService = sessionService;
    }

    @EventListener
    public void handleWebSocketConnectListener(SessionConnectedEvent event) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        log.info("用户 ：" + accessor);
        String sessionId = accessor.getSessionId();
        String userId = accessor.getFirstNativeHeader("user-id");

        if (userId != null) {
            sessionService.registerSession(userId, sessionId);
            sessionService.notifyUserStatus(userId, true);
        }

        System.out.println("【STOMP】客户端连接成功, SessionID: " + sessionId +
                         ", 用户ID: " + (userId != null ? userId : "未认证"));
    }

    @EventListener
    public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
        StompHeaderAccessor accessor = StompHeaderAccessor.wrap(event.getMessage());
        String sessionId = accessor.getSessionId();
        String userId = accessor.getUser() != null ? accessor.getUser().getName() : null;

        if (userId != null) {
            sessionService.removeSession(sessionId);
            sessionService.notifyUserStatus(userId, false);
        }

        System.out.println("【STOMP】客户端断开连接, SessionID: " + sessionId +
                         ", 用户ID: " + (userId != null ? userId : "未认证"));
    }
}